package order

import (
	"context"

	"entgo.io/ent/dialect/sql"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/combo"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/device"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/pancakebotorder"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPancakebotOrderByUserIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPancakebotOrderByUserIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPancakebotOrderByUserIdLogic {
	return &GetPancakebotOrderByUserIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetPancakebotOrderByUserIdLogic) GetPancakebotOrderByUserId(in *pancakebot.UUIDReq) (*pancakebot.GetPancakebotOrderByUserIdResp, error) {
	// 查询用户的所有订单
	orders, err := l.svcCtx.DB.PancakebotOrder.Query().
		Where(pancakebotorder.UserIDEQ(in.Id)).
		Order(pancakebotorder.ByCreatedAt(sql.OrderDesc())). // 按创建时间降序排列
		All(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 构建返回结果
	resp := &pancakebot.GetPancakebotOrderByUserIdResp{
		Total: uint64(len(orders)),
		Data:  make([]*pancakebot.GetPancakebotOrderInfo, 0, len(orders)),
	}

	// 如果没有订单,直接返回
	if len(orders) == 0 {
		return resp, nil
	}

	// 收集所有设备ID
	deviceIds := make([]uint64, 0, len(orders))
	deviceIdMap := make(map[uint64]bool)
	for _, order := range orders {
		if !deviceIdMap[order.DeviceID] {
			deviceIds = append(deviceIds, order.DeviceID)
			deviceIdMap[order.DeviceID] = true
		}
	}

	// 收集所有套餐ID
	comboIds := make([]uint64, 0, len(orders))
	comboIdMap := make(map[uint64]bool)
	for _, order := range orders {
		if !comboIdMap[order.ComboID] {
			comboIds = append(comboIds, order.ComboID)
			comboIdMap[order.ComboID] = true
		}
	}

	// 批量查询设备信息
	devices, err := l.svcCtx.DB.Device.Query().
		Where(device.IDIn(deviceIds...)).
		All(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 批量查询套餐信息
	combos, err := l.svcCtx.DB.Combo.Query().
		Where(combo.IDIn(comboIds...)).
		All(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 构建设备ID到设备名称的映射
	deviceNameMap := make(map[uint64]string, len(devices))
	for _, dev := range devices {
		deviceNameMap[dev.ID] = dev.DeviceName
	}

	// 构建套餐ID到套餐信息的映射
	comboMap := make(map[uint64]*ent.Combo, len(combos))
	for _, c := range combos {
		comboMap[c.ID] = c
	}

	// 转换订单数据
	for _, order := range orders {
		createdAt := order.CreatedAt.UnixMilli()

		deviceName := deviceNameMap[order.DeviceID]
		price := float32(order.Price)

		// 从map中获取套餐信息
		comboInfo, exists := comboMap[order.ComboID]
		if !exists {
			logx.Errorf("套餐ID %d 不存在", order.ComboID)
			continue
		}

		orderInfo := &pancakebot.GetPancakebotOrderInfo{
			Id:         &order.ID,
			CreatedAt:  &createdAt,
			DeviceName: &deviceName,
			ComboName:  &comboInfo.Name,
			ComboImage: &comboInfo.ImgAddr,
			OrderPayId: &order.PayOrderId,
			Price:      &price,

			PayStatus:       &order.PayStatus,
			ComboIngredient: order.ComboIngredient,
			OrderStatus:     &order.OrderStatus,
		}

		if order.OutletNo != nil {
			outletNo := int64(*order.OutletNo)
			orderInfo.OutletNo = &outletNo
		}

		if order.OutletTime != nil {
			outletTime := order.OutletTime.UnixMilli()
			orderInfo.OutletTime = &outletTime
		}

		// PayTime 是 time.Time 类型,需要检查是否为零值
		if !order.PayTime.IsZero() {
			payTime := order.PayTime.UnixMilli()
			orderInfo.PayTime = &payTime
		}

		resp.Data = append(resp.Data, orderInfo)
	}

	return resp, nil
}
